package com.ruoyi.verify.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.verify.mapper.VerifyPlanInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.verify.mapper.VerifyReportMapper;
import com.ruoyi.verify.mapper.VerifyTemplateContentMapper;
import com.ruoyi.verify.domain.VerifyQuestionnaire;
import com.ruoyi.verify.domain.VerifyReport;
import com.ruoyi.verify.service.IVerifyReportService;

import lombok.extern.slf4j.Slf4j;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ServletUtils;

/**
 * 审核结果Service业务层处理
 *
 * @author ruoyi
 * @date 2020-10-24
 */
@Service
@Slf4j
public class VerifyReportServiceImpl implements IVerifyReportService
{
    @Autowired
    private VerifyReportMapper verifyReportMapper;
    @Autowired
    private VerifyTemplateContentMapper verifyTemplateContentMapper;

    @Autowired
	private VerifyPlanInfoMapper verifyPlanInfoMapper;

    private static final String Ok = "1";

    /**
     * 查询审核结果
     *
     * @param reportid 审核结果ID
     * @return 审核结果
     */
    @Override
    public VerifyReport selectVerifyReportById(Long reportid)
    {
        return verifyReportMapper.selectVerifyReportById(reportid);
    }

    /**
     * 查询审核结果列表
     *
     * @param verifyReport 审核结果
     * @return 审核结果
     */
    @Override
    public List<VerifyReport> selectVerifyReportList(VerifyReport verifyReport)
    {
        return verifyReportMapper.selectVerifyReportList(verifyReport);
    }

    /**
     * 新增审核结果
     *
     * @param verifyReport 审核结果
     * @return 结果
     */
    @Override
    public int insertVerifyReport(VerifyReport verifyReport)
    {
        return verifyReportMapper.insertVerifyReport(verifyReport);
    }

    /**
     * 新增审核问题
     * @param problemid,content,type
     * @return
     */
    @SuppressWarnings("unchecked")
	@Override
    @Transactional(rollbackFor = Exception.class)
    public String insertVerifyProblem(Map<String, Object> datas)
    {
    	String result = Ok;
    	String loguser = ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);
    	Long reportid = Long.valueOf(String.valueOf(datas.get("reportid")));
    	Object fileidlist = datas.get("fileid");


		try {
			verifyReportMapper.deleteProblemByReportid(reportid);
		} catch (Exception e) {
			result = "审核问题删除失败，请联系管理员！";
			log.error(result,e);
			return result;
		}
    	VerifyReport verifyReport = new VerifyReport();

		//将文件id数组转为id字符串
		if(fileidlist!=null){
			List<Object> fileidArray = JSON.parseObject(JSON.toJSONString(fileidlist), List.class);
//			List<Object> fileidArray = JSON.parseArray(fileidlist.toString());
			List<String> fileids = fileidArray.stream().filter(f -> StringUtils.isNotNull(f)).map(f -> f.toString()).collect(Collectors.toList());
			if(fileids!=null && fileids.size()>0){
				verifyReport.setFileid(StringUtils.join(fileids,","));
			}
		}
    	verifyReport.setReportid(reportid);

    	verifyReport.setLogdate(new Date());
    	verifyReport.setLoguserid(loguser);
    	verifyReport.setMemo(String.valueOf(datas.get("memo")));
    	verifyReport.setHandovertime(String.valueOf((datas.get("handovertime"))));
    	verifyReport.setSupplierparticipants(String.valueOf((datas.get("supplierparticipants"))));
    	verifyReport.setSeriousinconsistent(String.valueOf(datas.get("seriousinconsistent")));

		try {
			verifyReportMapper.updateVerifyReport(verifyReport);
		} catch (Exception e) {
			result = "审核问题备注更新失败，请联系管理员！";
			log.error(result,e);
			return result;
		}
		List<HashMap<String, Object>> problemList = (List<HashMap<String, Object>>) datas.get("datas");
    	for (HashMap<String, Object> problem : problemList)
    	{
    		problem.put("loguser",loguser);
    		problem.put("logdate",new Date());
    		problem.put("reportid", reportid);
//			problem.put("handovertime",datas.get("handovertime"));
//			problem.put("supplierparticipants",datas.get("supplierparticipants"));
    		try {
				verifyReportMapper.insertVerifyProblem(problem);
			} catch (Exception e) {
				result = problem.get("content") + "添加失败，请联系管理员！";
				log.error(result,e);
				return result;
			}
    	}
    	return result;
    }

    /**
     * 修改审核结果
     *
     * @param verifyReport 审核结果
     * @return 结果
     */
    @Override
    public int updateVerifyReport(VerifyReport verifyReport)
    {
    	String loguser = ServletUtils.getRequest().getHeader(Constants.ACCESS_USERID);
    	verifyReport.setLoguserid(loguser);
    	verifyReport.setLogdate(new Date());
    	for (Map<String,Object> obj:verifyReport.getQuestionnaireidlist())
    	{
    		VerifyQuestionnaire verifyQuestionnaire = new VerifyQuestionnaire();
    		verifyQuestionnaire.setQuestionnaireid(String.valueOf(obj.get("questionnaireid")));
    		verifyQuestionnaire.setMemo(String.valueOf(obj.get("memo")));
    		verifyQuestionnaire.setLoguser(loguser);
    		verifyQuestionnaire.setLogdate(new Date());
    		verifyTemplateContentMapper.updateQuestionnaire(verifyQuestionnaire);
    	}
        return verifyReportMapper.updateVerifyReport(verifyReport);
    }

	/**
	 * 修改VDA6.3审核结果
	 *
	 * @param verifyReport 审核结果
	 * @return 结果
	 */
	@Override
	public int updateVdaVerifyReport(VerifyReport verifyReport)
	{
		String loguser = ServletUtils.getRequest().getHeader(Constants.ACCESS_USERID);
		verifyReport.setLoguserid(loguser);
		verifyReport.setLogdate(new Date());
		return verifyReportMapper.updateVerifyReport(verifyReport);
	}

    /**
     * 修改审核问题
     *
     * @param problem 审核问题
     * @return 结果
     */
    public String updateProblem(Map<String, List<HashMap<String, Object>>> datas)
    {
    	String result = Ok;
    	for (HashMap<String, Object> problem : datas.get("datas"))
    	{
//    		problem.put("loguserid",ServletUtils.getRequest().getHeader(Constants.ACCESS_USERID));
    		problem.put("Logdate",new Date());
    	    try {
				verifyReportMapper.updateProblem(problem);
			} catch (Exception e) {
				result = problem.get("content") + "修改失败，请联系管理员！";
				log.error(result,e);
				return result;
			}
    	}
    	return result;
    }


    /**
     * 删除审核结果对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteVerifyReportByIds(String ids)
    {
        return verifyReportMapper.deleteVerifyReportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核问题对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteProblemById(Long problemid)
    {
        return verifyReportMapper.deleteProblemById(problemid);
    }

	@Override
	public int releaseReport(String panid,Long reportid,Long globalcommit,String suppliername) {

		VerifyQuestionnaire verifyQuestionnaire = new VerifyQuestionnaire();
		verifyQuestionnaire.setPlanid(panid);
		verifyQuestionnaire.setVendorname(suppliername);
		verifyQuestionnaire.setStatus("Publish");
		verifyQuestionnaire.setType("Division");
		if(!verifyTemplateContentMapper.checkPublicCommit(verifyQuestionnaire)){//如果子计划全部提交，改变需求和计划状态
			verifyReportMapper.updateMainVerifyPlanStatus(String.valueOf(reportid));
			verifyReportMapper.updateVerifyRequirementStatus(String.valueOf(reportid));
		}
		return verifyPlanInfoMapper.updateVerifyPlanReportStatus(reportid,globalcommit);
	}

	@Override
	public List<HashMap<String, Object>> selectProblemListById(String planid, boolean ifteamleader) {
    	if(ifteamleader==true){
    		return verifyReportMapper.selectProblemById(planid);
		}
		String memberid = ServletUtils.getRequest().getHeader(Constants.ACCESS_USERID);
		return verifyReportMapper.selectProblemByUserId(planid,memberid);
	}

	@Override
	public List<Map<String, Object>> selectProblemListByClick(String planid) {
		return verifyReportMapper.selectProblemListByClick(planid);
	}

	@Override
	public int updateMainVerifyPlanStatus(String reportid) {
		return verifyReportMapper.updateMainVerifyPlanStatus(reportid);
	}

	/**
     * 删除审核结果信息
     *
     * @param reportid 审核结果ID
     * @return 结果
     */
    public int deleteVerifyReportById(Long reportid)
    {
        return verifyReportMapper.deleteVerifyReportById(reportid);
    }


}
